package xxl.ioc.dependencyproviders 
{
	import flash.utils.Dictionary;
	import xxl.ioc.Injector;
	import xxl.ioc.typedescriptions.PreDestroyInjectionPoint;
	import xxl.ioc.typedescriptions.TypeDescription;
	/**
	 * ...
	 * @author XXL
	 */
	public class SingletonProvider implements IDependencyProvider 
	{
		private var _responseType:Class;
		private var _creatingInjector:Injector;
		private var _response:Object;
		private var _destroyed:Boolean;
		
		public function SingletonProvider(responseType:Class, creatingInjector:Injector) 
		{
			_responseType = responseType;
			_creatingInjector = creatingInjector;
		}
		
		private function createResponse(injector:Injector):Object
		{
			if (_destroyed)
			{
				throw new Error("已被销毁");
			}
			return injector.instantiateUnmapped(_responseType);
		}
		
		/* INTERFACE xxl.ioc.dependencyproviders.IDependencyProvider */
		
		public function apply(targetType:Class, activeInjector:Injector, injectParameters:Dictionary):Object 
		{
			return _response ||= createResponse(_creatingInjector);
		}
		
		public function destroy():void 
		{
			_destroyed = true;
			if (!_response)
			{
				return;
			}
			const typeDescription:TypeDescription = _creatingInjector.getTypeDescription(_responseType);
			for (var preDestoryHook:PreDestroyInjectionPoint = typeDescription.preDestoryMethods;
				preDestoryHook;
				preDestoryHook = PreDestroyInjectionPoint(preDestoryHook.next))
			{
				preDestoryHook.applyInjection(_response, _responseType, _creatingInjector);
			}
			_response = null;
		}
		
	}

}